All files / Bandstand/src/app/api/members/[id]/password route.ts

0% Statements 0/57
0% Branches 0/1
0% Functions 0/1
0% Lines 0/57

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58                                                                                                                   
export const dynamic = 'force-dynamic'

import {prisma} from '@/lib/db'
import {requireAdmin} from '@/lib/guard'
import {canManageAccount} from '@/lib/band'
import {generatePassword, hashPassword} from '@/lib/password'
import {displayName, logActivity} from '@/lib/songs'
import {route} from '@/lib/route'

/**
 * Generate a new random password for a member and return it ONCE, for the
 * admin to send them. Only the hash is stored. Any session they already had
 * ends (sessionVersion is bumped).
 */
export const POST = route(
  async (_req: Request, {params}: {params: {id: string}}) => {
    const {user: admin, band} = await requireAdmin()
    const u = await prisma.user.findFirst({
      where: {id: params.id, memberships: {some: {bandId: band.id}}},
    })
    if (!u) return new Response('Not Found', {status: 404})
    if (!(await canManageAccount(admin, u.id)))
      return Response.json(
        {
          error:
            'They’re also in a band you don’t run, so ask its admin (or the person who runs this site) to reset it.',
        },
        {status: 403},
      )
    const password = generatePassword()
    const passwordHash = await hashPassword(password)
    await prisma.$transaction(async (tx) => {
      await tx.user.update({
        where: {id: u.id},
        data: {
          passwordHash,
          passwordSetAt: new Date(),
          sessionVersion: {increment: 1},
        },
      })
      await logActivity(tx, {
        bandId: band.id,
        userId: admin.id,
        action: u.passwordHash
          ? 'member.password.reset'
          : 'member.password.set',
        targetType: 'user',
        targetId: u.id,
        summary: `${u.passwordHash ? 'reset' : 'set'} ${u.id === admin.id ? 'their own' : `${displayName(u)}’s`} password`,
      })
    })
    return Response.json(
      {password},
      {status: 201, headers: {'Cache-Control': 'no-store'}},
    )
  },
)